<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" size="mini" style="width: 200px" class="filter-item" placeholder="姓名或账户"
                v-model="listQuery.username"></el-input>
      <el-button class="filter-item" type="primary" size="mini" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" v-if="userManager_btn_add" size="mini" style="margin-left: 10px" @click="handleCreate"
                 type="primary" icon="el-icon-circle-plus-outline">添加
      </el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" size="mini" border fit highlight-current-row
              style="width: 100%">

      <el-table-column align="center" label="id" min-width="210" v-if="false">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" align="center" label="用户">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" align="center" label="密码" type=”password”>
        <template slot-scope="scope">
          <span>{{ '**********'}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="185px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createdatetime}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="185px" align="center" label="修改时间">
        <template slot-scope="scope">
          <span>{{scope.row.modifydatetime}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200px" align="center" label="角色id" v-if="false">
        <template slot-scope="scope">
          <span>{{scope.row.roleId}}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="185">
        <template slot-scope="scope">
          <el-button v-if="userManager_btn_edit" icon="el-icon-edit" size="mini" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="userManager_btn_del" icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
                     :current-page.sync="listQuery.page" :page-sizes="[5,10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="用户" prop="username" size="mini">
          <el-input v-model="form.username" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入" size="mini"></el-input>
        </el-form-item>
        <!--<el-form-item label="创建时间" prop="createdatetime">-->
          <!--<el-input v-model="form.createdatetime" placeholder="请输入"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="修改时间" prop="modifydatetime">-->
          <!--<el-input v-model="form.modifydatetime" placeholder="请输入"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="角色id" prop="roleId" v-if="this.dialogStatus === 'update'">
          <el-input v-model="form.roleId" placeholder="请输入" v-if="false"></el-input>
          <div>
            <b-btn v-b-modal.modalPrevent>请选择资源</b-btn>
            <!-- Modal Component -->
            <b-modal id="modalPrevent"
                     ref="modal"
                     title="选择资源"
                     centered
                     ok-title="确定"
                     cancel-title="取消"
                     button-size="sm"
                     @ok="handleOk"
                     @shown="initTree">
              <ul id="roleList" class="ztree"></ul>
            </b-modal>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')"  size="mini">取 消</el-button>
        <el-button v-if="dialogStatus=='create'"  size="mini" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary"  size="mini" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleAll,
  getRoleByUserId,
  insertUserAndRole,
  page,
  addObj,
  getObj,
  delObj,
  putObj
} from '../../../api/yun/user/index'
import {mapGetters} from 'vuex'
import $ from 'jquery'
import 'ztree'
import 'ztree/css/metroStyle/metroStyle.css'
import '../../../../static/bootstrapStyle.css'
// import { MessageBox } from 'element-ui'
export default {
  name: 'user',
  data () {
    return {
      ztree: {
        roleIds: [],
        roleList: null,
        roleListByUserId: null
      },
      setting: {
        view: {
          selectedMulti: false,
          showIcon: true // 是否显示图标
        },
        check: {
          enable: true,
          chkboxType: { 'Y': 's', 'N': 's' }
        },
        data: {
          key: {
            url: 'xUrl',
            icon: 'conx'
          },
          simpleData: {
            enable: true,
            idkey: 'id',
            pIdKey: 'pid',
            rootPid: null
          }
        },
        edit: {
          enable: false
        }},
      form: {
        username: undefined,
        password: undefined,
        createdatetime: undefined,
        modifydatetime: undefined,
        roleId: undefined
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        createdatetime: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        modifydatetime: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        roleId: [
          {
            required: false,
            message: '请输入',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      list: null,
      list2: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 5,
        username: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      userManager_btn_edit: false,
      userManager_btn_del: false,
      userManager_btn_add: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableKey: 0
    }
  },
  created () {
    this.getList()
    // this.list2 = this.$store.getters.routers
    // this.getBreadcrumb()
  },
  computed: {
    ...mapGetters([
      'routes'
    ])
  },
  methods: {
    initTree () {
      if (this.ztree.roleList.length > 0 && this.ztree.roleListByUserId.length > 0) {
        this.ztree.roleList.forEach((item, index) => {
          this.ztree.roleList[index].checked = false
          this.ztree.roleListByUserId.forEach((item2, index2) => {
            if (item.id === item2.id) {
              this.ztree.roleList[index].checked = true
            }
          })
        })
      }
      $.fn.zTree.init($('#roleList'), this.setting, this.ztree.roleList)
    },
    handleOk (evt) {
      evt.preventDefault()
      var treeObj = $.fn.zTree.getZTreeObj('roleList')
      var nodes = treeObj.getCheckedNodes(true)
      var _this = this

      _this.ztree.roleIds = '' // 先清空防止缓存
      console.log('nodes :' + nodes + ' ' + nodes.length)
      if (nodes.length >= 0) {
        nodes.forEach((item, index) => {
          _this.ztree.roleIds = _this.ztree.roleIds + item.id + ','
        })
        insertUserAndRole({roleIds: _this.ztree.roleIds, userId: _this.form.id}).then(response => {
          _this.$message({
            message: response.message,
            type: 'success'
          })
        })
        this.$refs.modal.hide()
      }
    },
    getBreadcrumb () {
      // return this.list2[this.list2.length - 1].name
    },
    getList () {
      this.listLoading = true
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        }).catch(() => {
          this.$message({
            message: '您没有权限操作',
            type: 'warning'
          })
          this.listLoading = false
        })
      // console.log('routes:' + this.$store.getters.routes)
    },
    handleFilter () {
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.getList()
    },
    handleCreate () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate (row) {
      getObj(row.id)
        .then(response => {
          this.form = response.data
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })
      getRoleByUserId({id: row.id}).then(response => {
        this.ztree.roleListByUserId = response.data.roleList
      })
      getRoleAll().then(response => {
        this.ztree.roleList = response.data
      })
    },
    handleDelete (row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
              this.total = this.total - 1
            })
        })
    },
    create (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form)
            .then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
        } else {
          return false
        }
      })
    },
    cancel (formName) {
      this.dialogFormVisible = false
      const set = this.$refs
      set[formName].resetFields()
    },
    update (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          delete this.form['createdatetime']
          delete this.form['modifydatetime']
          delete this.form['createdatetimeStart']
          delete this.form['createdatetimeEnd']
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    resetTemp () {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        password: undefined,
        description: undefined
      }
    }
  },
  beforeUpdate: function () {
    var pre = '/' + this.$route.path.split('/').pop()
    this.$store.getters.resources.forEach(item => {
      if (item.url === (pre + '/add')) {
        this.userManager_btn_add = true
      }
      if (item.url === (pre + '/update')) {
        this.userManager_btn_edit = true
      }
      if (item.url === (pre + '/delete')) {
        this.userManager_btn_del = true
      }
    })
  }
}
</script>
